from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework_jwt.views import Response
from django.core.cache import cache
from django.conf import settings
from video import models as video_models
from . import models, serializers

# 访问量大且数据一段时间内较为固定的接口，可以左接口缓存
# 1）从缓存中拿，有直接返回，没有查询数据库
# 2）查询数据库的数据返回给前台，同时将数据建立缓存
class BannerListAPIView(ListAPIView):
    queryset = models.Banner.objects.filter(is_show=True).order_by("-order")[:settings.BANNER_COUNT]
    serializer_class = serializers.BannerModelSerializer
    def get(self, request, *args, **kwargs):
        banner_list = cache.get('banner_list')
        if not banner_list:
            print('走数据库了')
            response = self.list(request, *args, **kwargs)
            # response.data不是json数据，是drf中的自定义ReturnList类
            cache.set('banner_list', response.data)  # 缓存不设过期时间，更新任务交给celery异步任务框架
            return response
        return Response(banner_list)


'''推荐数据接口'''
class RecommendListAPIView(APIView):
    def get(self, request, *args, **kwargs):
        # 查询缓存
        recommend_video_dic = cache.get('recommend_video_dic')
        if not recommend_video_dic:
            # 查询所有分类
            category_list = video_models.Category.objects.all()
            recommend_video_dic = {}
            # 根据分类取推荐表推荐个数的记录并进行序列化
            for category in category_list:
                queryset = models.Recommend.objects.filter(is_show=True, category_id=category.pk).order_by("-heat")[:settings.RECOMMEND_COUNT]
                recommend_video_dic[category.name] = serializers.RecommendModelSerializer(queryset,many=True).data
            response = Response(recommend_video_dic)
            cache.set('recommend_video_dic', response.data)  # 缓存不设过期时间，更新任务交给celery异步任务框架
            return response
        return Response(recommend_video_dic)
